﻿using System;
using System.Text.RegularExpressions;
using Jink.Core.Converters.Annotations;
using System.Linq;
using Jink.Core.Json;
using Jink.Core.Json.Values;
using XenoGears.Assertions;
using PairOfStrings = System.Collections.Generic.KeyValuePair<System.String, System.String>;

namespace Jink.Core.Handlers.Bind.Converters
{
    [Converter]
    internal static class QueryStringConverter
    {
        // todo. this will work incorrectly with query string KVPs 
        // that contains question marks (?) and/or ampersands (&)

        [Converter(Weight = 0.9)]
        public static JsonValue QueryStringKvpToAnonymous(String qs)
        {
            return new JsonObject(qs.Split('&').Select(part =>
            {
                var match = Regex.Match(part, "^(?<key>.*)=(?<value>.*)$");
                match.Success.AssertTrue();

                var key = match.Result("${key}");
                var value = match.Result("${value}");
                return new PairOfStrings(key, value);
            }).ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToJson()));
        }
    }
}
